package com.strawcom.charmring.ui.fragment;

import java.util.ArrayList;
import java.util.List;

import android.widget.Toast;
import com.strawcom.charmring.ui.MainActivity;
import org.litepal.crud.DataSupport;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.location.Location;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.location.LocationManagerProxy;
import com.amap.api.location.LocationProviderProxy;
import com.amap.api.maps.AMap;
import com.amap.api.maps.AMap.OnInfoWindowClickListener;
import com.amap.api.maps.AMap.OnMarkerClickListener;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.LocationSource;
import com.amap.api.maps.MapView;
import com.amap.api.maps.model.BitmapDescriptor;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.MyLocationStyle;
import com.strawcom.charmring.BaseFragment;
import com.strawcom.charmring.PushReceiver;
import com.strawcom.charmring.R;
import com.strawcom.charmring.bean.Alert;
import com.strawcom.charmring.util.LogUtil;
import com.strawcom.charmring.view.HeadHorizontalScrollView;
import com.strawcom.charmring.view.HeadHorizontalScrollView.OnSelectedChangedListener;
import com.strawcom.charmring.view.MapFrameLayout;
import com.strawcom.charmring.view.SlideCutListView;
import com.strawcom.charmring.view.SlideCutListView.RemoveDirection;
import com.strawcom.charmring.view.SlideCutListView.RemoveListener;

/**
 * 
 * @ClassName: LocationFragment
 * @Description:定位Fragment
 * @author liyongqiang
 * @date 2015-3-30 下午11:44:55
 * 
 */
@SuppressWarnings("deprecation")
public class LocationFragment extends BaseFragment implements LocationSource, OnClickListener, OnMarkerClickListener,
		OnInfoWindowClickListener {

	private MapView mapView;
	private AMap aMap;
	private View mapLayout;
	private LocationManagerProxy mAMapLocationManager;
	private HeadHorizontalScrollView layoutHead;
	private MapFrameLayout layoutMapFrame;
	private SlideCutListView listView;
	private Button btnFriendAlert;
	private Button btnAllAlert;
	private final List<Alert> alertAllInfoList = new ArrayList<Alert>();
	private final List<Alert> adapterList = new ArrayList<Alert>();
	private final List<Alert> userList = new ArrayList<Alert>();
	private static final int WHICH_FRIEND = 1;
	private static final int WHICH_ALL = 2;
	private int which = WHICH_FRIEND;
	private int selectedPosition = -1;

	private Marker selfMarker;
	private boolean selfLocation;

	@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		if (mapLayout == null) {
			mapLayout = inflater.inflate(R.layout.fragment_location, container, false);
			mapView = (MapView) mapLayout.findViewById(R.id.map);
			mapView.onCreate(savedInstanceState);
			if (aMap == null) {
				aMap = mapView.getMap();
				aMap.setOnMarkerClickListener(this);// 设置点击marker事件监听器
				aMap.setOnInfoWindowClickListener(this);

				// 自定义系统定位蓝点
				MyLocationStyle myLocationStyle = new MyLocationStyle();
				// 自定义定位蓝点图标
				myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker));
				// 自定义精度范围的圆形边框颜色
				myLocationStyle.strokeColor(Color.BLACK);
				// 自定义精度范围的圆形边框宽度
				myLocationStyle.strokeWidth(5);
				// 将自定义的 myLocationStyle 对象添加到地图上
				aMap.setMyLocationStyle(myLocationStyle);
				// 构造 LocationManagerProxy 对象
				mAMapLocationManager = LocationManagerProxy.getInstance(holderActivity);
				// 设置定位资源。如果不设置此定位资源则定位按钮不可点击。
				aMap.setLocationSource(this);
				// 设置默认定位按钮是否显示
				aMap.getUiSettings().setMyLocationButtonEnabled(true);
				// 设置为true表示显示定位层并可触发定位，false表示隐藏定位层并不可触发定位，默认是false
				aMap.setMyLocationEnabled(true);

				mAMapLocationManager.requestLocationUpdates(LocationProviderProxy.AMapNetwork, 2000, 10, mAMapLocationListener);
			}
		}
		else {
			if (mapLayout.getParent() != null) {
				((ViewGroup) mapLayout.getParent()).removeView(mapLayout);
			}
		}

		layoutMapFrame = (MapFrameLayout) mapLayout.findViewById(R.id.layout_map_frame);
		layoutHead = (HeadHorizontalScrollView) mapLayout.findViewById(R.id.layout_head);
		layoutHead.setOnHeadClickListener(headClickListener);
		listView = (SlideCutListView) mapLayout.findViewById(R.id.msg_listview);
		listView.setAdapter(alarmMessageAdapter);
		listView.setRemoveListener(new RemoveListener() {
			@Override public void removeItem(RemoveDirection direction, int position) {
				Alert delAlert = adapterList.get(position);
				delAlert.delete();

				adapterList.remove(position);
				alarmMessageAdapter.notifyDataSetChanged();
			}
		});

		btnFriendAlert = (Button) mapLayout.findViewById(R.id.btn_friend_alert);
		btnAllAlert = (Button) mapLayout.findViewById(R.id.btn_all_alert);
		btnFriendAlert.setOnClickListener(this);
		btnAllAlert.setOnClickListener(this);

		setUpMap();

		setAlertInfo();

		registerRingMessageReceiver();

		return mapLayout;
	}

	private void setAlertInfo() {
		alertAllInfoList.clear();
		List<Alert> alertList = DataSupport.order("date desc").find(Alert.class);
		if (alertList == null || alertList.size() < 1) {
			LogUtil.e("alertList empty");
			layoutMapFrame.setVisibility(View.GONE);
			return;
		}
		layoutMapFrame.setVisibility(View.VISIBLE);
		alertAllInfoList.addAll(alertList);

		userList.clear();
		for (Alert alert : alertAllInfoList) {
			if (!userList.contains(alert)) {
				userList.add(alert);
			}
		}

		int position = userList.size() / 2;
		if (selectedPosition == -1 || selectedPosition > userList.size() - 1) {
			selectedPosition = position;
		}
		if (userList.size() > 0) {
			layoutHead.setHeadList(userList, selectedPosition, layoutMapFrame);

			showInfoOnMap(userList.get(selectedPosition), selectedPosition);
		}

		Alert curr = userList.get(selectedPosition);
		btnFriendAlert.setText(String.format(getString(R.string.alert_info_title), curr.getName()));

		notifyDataSetChanged();
	}

	/**
	 * 自身定位
	 */
	private AMapLocationListener mAMapLocationListener = new AMapLocationListener() {
		@Override public void onStatusChanged(String provider, int status, Bundle extras) {
		}

		@Override public void onProviderEnabled(String provider) {
		}

		@Override public void onProviderDisabled(String provider) {
		}

		@Override public void onLocationChanged(Location location) {
		}

		@Override public void onLocationChanged(AMapLocation location) {
			if (location != null&& !((MainActivity) getActivity()).fromPush) {
				String title = getString(R.string.map_my_location);
				String info = location.getDistrict() + location.getStreet() + getString(R.string.location_near) + location.getPoiName();
				showInfoOnMap(title, info, location.getLatitude(), location.getLongitude());

				if (!selfLocation) {
					deactivate();
					activate(null);
					selfLocation = true; // 初次定位，速度发动快为2秒，之后改为10秒一刷新。
				}
			}
		}
	};

	private OnSelectedChangedListener headClickListener = new OnSelectedChangedListener() {
		@Override public void onSelectedChanged(int position) {
			selectedPosition = position;
			notifyDataSetChanged();

			showInfoOnMap(userList.get(position), position);
		}
	};

	private void notifyDataSetChanged() {
		adapterList.clear();
		if (which == WHICH_ALL) {
			adapterList.addAll(alertAllInfoList);
		}
		else if (which == WHICH_FRIEND) {
			String phonenum = userList.get(selectedPosition).getPhonenum();
			for (Alert alert : alertAllInfoList) {
				if (alert.getPhonenum().equals(phonenum)) {
					adapterList.add(alert);
				}
			}
		}
		alarmMessageAdapter.notifyDataSetChanged();
	}

	BitmapDescriptor mapBitmapDescriptor = BitmapDescriptorFactory.fromResource(R.drawable.ico_position);

	private void showInfoOnMap(Alert alert, final int position) {
		String title = alert.getName();
		String snippet = alert.getMsg();
		LatLng latlng = new LatLng(alert.getLat(), alert.getLng());
		aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
		// 设置远小近大效果,2.1.0版本新增；设置刷新一次图片资源的周期。
		Marker marker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).position(latlng).title(title).snippet(snippet)
				.icon(mapBitmapDescriptor).draggable(false).period(50));
		marker.showInfoWindow();// 设置默认显示一个infoWinfow
		marker.setObject(position);
	}

	public void showInfoOnMap(String title, String address, double lat, double lng) {
		
		String snippet = address;
		LatLng latlng = new LatLng(lat, lng);
		if (selfMarker == null) {
			aMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 15));
		}
		else {
			selfMarker.remove();
		}
		selfMarker = aMap.addMarker(new MarkerOptions().anchor(0.5f, 0.5f).position(latlng).title(title).snippet(snippet)
				.icon(mapBitmapDescriptor).draggable(false).period(50));
		selfMarker.showInfoWindow();// 设置默认显示一个infoWinfow
	}

	private void setUpMap() {

		MyLocationStyle myLocationStyle = new MyLocationStyle();
		// myLocationStyle.myLocationIcon(BitmapDescriptorFactory.fromResource(R.drawable.location_marker));//
		// 设置小蓝点的图标
		myLocationStyle.myLocationIcon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
		myLocationStyle.strokeColor(Color.TRANSPARENT);// 设置圆形的边框颜色
		myLocationStyle.radiusFillColor(Color.TRANSPARENT);// 设置圆形的填充颜色
		// myLocationStyle.anchor(int,int)//设置小蓝点的锚点
		myLocationStyle.strokeWidth(1.0f);// 设置圆形的边框粗细
		aMap.setMyLocationStyle(myLocationStyle);
		aMap.setLocationSource(this);// 设置定位监听
		aMap.getUiSettings().setMyLocationButtonEnabled(false);// 设置默认定位按钮是否显示
		aMap.setMyLocationEnabled(true);// 设置为true表示显示定位层并可触发定位
		aMap.setMyLocationType(AMap.LOCATION_TYPE_MAP_FOLLOW);// 设置定位的类型为定位模式
																// ，可以由定位、跟随或地图根据面向方向旋转几种
	}

	@Override public void onResume() {
		super.onResume();
		mapView.onResume();
		activate(null);
	}

	/**
	 * 方法必须重写 map的生命周期方法
	 */
	@Override public void onPause() {
		super.onPause();
		mapView.onPause();
		deactivate();
	}

	/**
	 * 方法必须重写 map的生命周期方法
	 */
	@Override public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		mapView.onSaveInstanceState(outState);
	}

	/**
	 * 方法必须重写 map的生命周期方法
	 */
	@Override public void onDestroy() {
		super.onDestroy();
		mapView.onDestroy();

		unregisterRingMessageReceiver();
	}

	/**
	 * 激活定位
	 */
	@Override public void activate(OnLocationChangedListener listener) {
		if (mAMapLocationManager == null) {
			mAMapLocationManager = LocationManagerProxy.getInstance(getActivity());
			mAMapLocationManager.requestLocationData(LocationProviderProxy.AMapNetwork, 10000, 30, mAMapLocationListener);
			mAMapLocationManager.setGpsEnable(false);
		}
	}

	/**
	 * 停止定位
	 */
	@Override public void deactivate() {
		if (mAMapLocationManager != null) {
			mAMapLocationManager.removeUpdates(mAMapLocationListener);
			mAMapLocationManager.destory();
		}
		mAMapLocationManager = null;
	}

	@Override public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_friend_alert:
			btnFriendAlert.setBackgroundResource(R.drawable.border_map_frame_title_left_select);
			btnAllAlert.setBackgroundResource(R.drawable.border_map_frame_title_right_normal);

			which = WHICH_FRIEND;
			notifyDataSetChanged();
			break;
		case R.id.btn_all_alert:
			btnFriendAlert.setBackgroundResource(R.drawable.border_map_frame_title_left_normal);
			btnAllAlert.setBackgroundResource(R.drawable.border_map_frame_title_right_select);
			which = WHICH_ALL;
			notifyDataSetChanged();
			break;
		default:
			break;
		}
	}

	BaseAdapter alarmMessageAdapter = new BaseAdapter() {

		@Override public View getView(int poiston, View convertView, ViewGroup parent) {
			ViewHolder viewHolder = null;
			if (convertView == null) {
				viewHolder = new ViewHolder();
				convertView = LayoutInflater.from(getActivity()).inflate(R.layout.item_msg, null);
				viewHolder.tvName = (TextView) convertView.findViewById(R.id.tv_name);
				viewHolder.tvMsg = (TextView) convertView.findViewById(R.id.tv_msg);
				viewHolder.tvTime = (TextView) convertView.findViewById(R.id.tv_time);
				viewHolder.tvAddr = (TextView) convertView.findViewById(R.id.tv_addr);
				convertView.setTag(viewHolder);
			}
			else {
				viewHolder = (ViewHolder) convertView.getTag();
			}
			Alert alert = adapterList.get(poiston);
			viewHolder.tvName.setText(alert.getName());
			viewHolder.tvMsg.setText(alert.getMsg());
			viewHolder.tvTime.setText(alert.getDate());
			viewHolder.tvAddr.setText("test");
			return convertView;
		}

		@Override public long getItemId(int id) {
			return id;
		}

		@Override public Object getItem(int poistion) {
			return adapterList.get(poistion);
		}

		@Override public int getCount() {
			return adapterList.size();
		}

		class ViewHolder {
			TextView tvName;
			TextView tvMsg;
			TextView tvTime;
			TextView tvAddr;
		}
	};

	private void registerRingMessageReceiver() {
		if (holderActivity != null) {
			IntentFilter filter = new IntentFilter();
			filter.addAction(PushReceiver.ACTION_ALERT);
			holderActivity.registerReceiver(ringMessageReceiver, filter);
		}
	}

	private void unregisterRingMessageReceiver() {
		if (holderActivity != null) {
			holderActivity.unregisterReceiver(ringMessageReceiver);
		}
	}

	private final BroadcastReceiver ringMessageReceiver = new BroadcastReceiver() {
		@Override public void onReceive(Context context, Intent intent) {

			final String action = intent.getAction();
			if (PushReceiver.ACTION_ALERT.equals(action)) {
				setAlertInfo();
				
				double lat = intent.getDoubleExtra(PushReceiver.EXTRA_LAT, 0);
				double lng =intent.getDoubleExtra(PushReceiver.EXTRA_LNG, 0);
				
			}
		}
	};

	@Override public void onInfoWindowClick(Marker marker) {
		int position = (Integer) marker.getObject();
		layoutHead.setSelection(position);
	}

	@Override public boolean onMarkerClick(Marker marker) {
		int position = (Integer) marker.getObject();
		layoutHead.setSelection(position);
		return false;
	}

}
